package com.beiding.fastmock.fram;

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.runtime.Undefined;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 丁常磊
 * @date 2021/7/14 13:02
 */

public class ScriptController {

    private ScriptObjectMirror controller;

    public ScriptController(ScriptObjectMirror controller) {
        this.controller = controller;
    }

    @ResponseBody
    public Object handle(
            @PathVariable(required = false) Map<String, Object> variable,
            @RequestHeader(required = false) MultiValueMap<String, String> header,
            @RequestParam(required = false) Map<String, Object> param,
            @RequestBody(required = false) byte[] body,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession session
    ) {

        RequestHolder paramHolder = new RequestHolder();
        paramHolder.setVariable(new HashMap<>(variable));
        paramHolder.setHeader(new LinkedMultiValueMap<>(header));
        paramHolder.setParam(new HashMap<>(param));
        paramHolder.setBody(body);
        paramHolder.setRequest(request);
        paramHolder.setResponse(response);
        paramHolder.setSession(session);
        paramHolder.controller = controller;
        Object r = controller.callMember("handle", paramHolder);
        if (r instanceof Undefined) {
            return null;
        }
        return r;
    }

}
